<template>
  <div class="login-form-wrapper">
    <div class="login-form-title">统一身份登录</div>
    <!-- <div class="login-form-sub-title">{{ $t('login.form.title') }}</div> -->
    <a-form
      ref="loginForm"
      :model="userInfo"
      class="login-form"
      layout="vertical"
      style="position: relative"
      @submit="handleSubmit"
    >
      <span
        class="login-form-error-msg"
        style="position: absolute; top: -30px"
        >{{ errorMessage }}</span
      >
      <a-form-item
        label="用户名"
        field="username"
        :rules="[{ required: true, message: $t('login.form.userName.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-asterisk
      >
        <a-input
          v-model="userInfo.username"
          :placeholder="$t('login.form.userName.placeholder')"
        >
          <template #prefix>
            <icon-user style="font-size: 16px" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item
        label="密码"
        field="password"
        :rules="[{ required: true, message: $t('login.form.password.errMsg') }]"
        :validate-trigger="['change', 'blur']"
        hide-asterisk
      >
        <a-input-password
          v-model="userInfo.password"
          :placeholder="$t('login.form.password.placeholder')"
          allow-clear
        >
          <template #prefix>
            <icon-lock style="font-size: 16px" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-space :size="16" direction="vertical">
        <div class="login-form-password-actions">
          <a-checkbox
            checked="rememberPassword"
            :model-value="loginConfig.rememberPassword"
            @change="setRememberPassword as any"
          >
            {{ $t('login.form.rememberPassword') }}
          </a-checkbox>
          <!-- <a-link>{{ $t('login.form.forgetPassword') }}</a-link> -->
        </div>
        <a-button
          type="primary"
          html-type="submit"
          long
          :loading="loading"
          style="margin-top: 65px"
        >
          {{ $t('login.form.login') }}
        </a-button>
        <!-- <a-button type="text" long class="login-form-register-btn">
          {{ $t('login.form.register') }}
        </a-button> -->
      </a-space>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue';
  import { useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import { ValidatedError } from '@arco-design/web-vue/es/form/interface';
  import { useI18n } from 'vue-i18n';
  import { useStorage } from '@vueuse/core';
  import { useUserStore, useAppStore } from '@/store';
  import useLoading from '@/common/hooks/loading';
  import type { LoginInfo } from '@/api/model/securityModel';

  const router = useRouter();
  const { t } = useI18n();
  const errorMessage = ref('');
  const { loading, setLoading } = useLoading();
  const userStore = useUserStore();
  const appStore = useAppStore();

  const menuPattern = computed(() => appStore.menuPattern);

  const loginConfig = useStorage('login-config', {
    rememberPassword: false,
    username: '', // 演示默认值
    password: '', // demo default value
  });
  const userInfo = reactive({
    username: loginConfig.value.username,
    password: loginConfig.value.password,
  });

  const handleSubmit = async ({
    errors,
    values,
  }: {
    errors: Record<string, ValidatedError> | undefined;
    values: Record<string, any>;
  }) => {
    if (loading.value) return;
    if (!errors) {
      setLoading(true);
      try {
        await userStore.login({
          username: values.username,
          password: window.btoa(values.password),
          // client_id: 'c1',
          // client_secret: 'secret',
          // grant_type: 'password',
        } as LoginInfo);
        const { redirect, ...othersQuery } = router.currentRoute.value.query;
        const toName = menuPattern.value === 1 ? 'rootMenu' : 'Workplace';
        if (redirect) {
          // 有redirect的时候需要先等待权限和用户信息加载完毕才能跳转
          router.push({
            name: 'Buff',
            query: {
              ...othersQuery,
              redirect,
            },
          });
        } else {
          router.push({
            name: toName,
            query: {
              ...othersQuery,
            },
          });
        }
        Message.success(t('login.form.login.success'));
        const { rememberPassword } = loginConfig.value;
        const { username, password } = values;
        // 实际生产环境需要进行加密存储。
        // The actual production environment requires encrypted storage.
        loginConfig.value.username = rememberPassword ? username : '';
        loginConfig.value.password = rememberPassword ? password : '';
      } catch (err) {
        errorMessage.value = (err as Error).message;
      } finally {
        setLoading(false);
      }
    }
  };
  const setRememberPassword = (value: boolean) => {
    loginConfig.value.rememberPassword = value;
  };
</script>

<style lang="less" scoped>
  :deep(.arco-icon) {
    font-size: 16px;
  }

  .login-form {
    // &-wrapper {
    // }
    &-title {
      margin-bottom: 60px;
      color: var(--color-text-1);
      font-weight: bold;
      font-size: 22px;
    }

    &-sub-title {
      color: var(--color-text-3);
      font-size: 16px;
      line-height: 24px;
    }

    &-error-msg {
      height: 32px;
      color: rgb(var(--red-6));
      line-height: 32px;
    }

    &-password-actions {
      display: flex;
      justify-content: space-between;
    }

    &-register-btn {
      color: var(--color-text-3) !important;
    }
  }
</style>
